package com.tensquare.user.service;

import com.tensquare.user.dao.AdminDao;
import com.tensquare.user.pojo.Admin;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


//他是一个管路员的service层
@Service
public class AdminService {
    @Autowired
    private AdminDao adminDao;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 管理与那登录
     */

    public Admin login(Admin admin){
        //先根据用户名查询对象
        Admin adminLogin = adminDao.findByLoginname(admin.getLoginname());
        //然后拿数据库中的密码和用户输入的密码匹配是否相同,第一个参数前端传递的明文，第二个参数数据库密文
        if (null!=adminLogin && encoder.matches(admin.getPassword(),adminLogin.getPassword())){
            //登录成功
            return adminLogin;
        }
        //登录失败
        return null;
    }



    //查询全部管理员信息
    public List<Admin> findAll(){
        return adminDao.findAll();
    }


    //根据ID查询管理员
    public Admin  findById(String id){
        return adminDao.findById(id).get();
    }


    //增
    public void add(Admin admin){
        admin.setId(idWorker.nextId()+"");
        //密码加密
        admin.setPassword(encoder.encode(admin.getPassword()));
        adminDao.save(admin);
    }
    //删
    public void  deleteById(String id){
//        //判断是否有头信息,所以注入一个requaest
//        String header = request.getHeader("Authorization");
//        if (null == header || "".equals(header)){
//            throw new RuntimeException("权限不足!");
//        }
//        if (!header.startsWith("Bearer ")){
//            throw new RuntimeException("权限不足!");
//        }
//        //得到token
//        String token = header.substring(7);
//        //token没判空
//        if (null == token || "".equals(token)){
//            throw new RuntimeException("权限不足!");
//        }
//        try{
//            Claims claims = jwtUtil.parseJWT(token);
//            String roles = (String) claims.get("roles");
//            if (null == roles || !roles.equals("admin")){
//                throw new RuntimeException("权限不足!");
//            }
//        }catch (Exception e){
//            throw new RuntimeException("权限不足!");
//        }
        String token = (String) request.getAttribute("claims_admin");
        if (null == token || "".equals(token)){
            throw new RuntimeException("权限不足!");
        }
        adminDao.deleteById(id);
    }


    //改
    public void update(Admin admin){
        adminDao.save(admin);
    }
}
